﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;

using SharedGenomics.Workbench.Core;

namespace SharedGenomics.Workbench.Presenters
{
    public class LoginPresenter : Presenter, ILoginPresenter
    {
        public LoginPresenter(ILoginView view, ILoginManager loginManager)
            : base(view)
        {
            this.LoginView = view;
            this.LoginManager = loginManager;

            view.LoginStarted += new EventHandler(this.View_LoginStarted);
        }

        private void View_LoginStarted(object sender, EventArgs e)
        {
            this.Login();
        }

        protected void Login()
        {
            //get username and password from the view
            string username = this.LoginView.Username;
            SecureString password = this.LoginView.Password;

            //show the progress bar and disable the login button
            this.LoginView.IsProgressBarVisible = true;
            this.LoginView.LoginEnabled = false;

            //try to login
            this.BackgroundExecutor.Execute(() =>
            {
                string errorMessage;
                this.IsLoggedIn = this.LoginManager.TryLogin(username, password, out errorMessage);

                //set the login message
                this.LoginView.LoginMessage = this.IsLoggedIn ?
                    "Login successful" :
                    String.Format("Login failed: {0}", errorMessage);
            },
            (r) =>
            {
                //hide the progress bar
                this.LoginView.IsProgressBarVisible = false;

                //re-enable the login button if the login failed
                if (this.IsLoggedIn)
                    this.RequestClose();
                else
                    this.LoginView.LoginEnabled = true;
            });
        }

        private ILoginView LoginView { get; set; }
        private ILoginManager LoginManager { get; set; }

        public bool IsLoggedIn { get; private set; }
    }
}
